package cn.org.zx.common.commutils;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.stereotype.Component;

import java.io.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 类的描述
 *
 * @author Zhihui.Wang
 * @version v1.0.0
 * @desc
 * @date 2019/6/10 15:36
 */
@Component
public class FTPUtils {
    private static final Logger log = LoggerFactory.getLogger(FTPUtils.class);

    /**
     * ftp服务器地址
     */
    private static String HOSTNAME = "47.101.159.1";
    /**
     * ftp服务器端口号默认为21
     */

    private static Integer PORT = 21;
    /**
     * ftp登录账号
     */
    private static String USERNAME = "userftp";
    /**
     * ftp登录密码
     */
    private static String PASSWORD = "1Qazxsw23edc";

    
    public void setHOSTNAME(String HOSTNAME) {
        FTPUtils.HOSTNAME = HOSTNAME;
    }

    public void setPORT(Integer PORT) {
        FTPUtils.PORT = PORT;
    }

    public void setUSERNAME(String USERNAME) {
        FTPUtils.USERNAME = USERNAME;
    }

    public void setPASSWORD(String PASSWORD) {
        FTPUtils.PASSWORD = PASSWORD;
    }


    public static String getHOSTNAME() {
        return HOSTNAME;
    }

    public static Integer getPORT() {
        return PORT;
    }

    public static String getUSERNAME() {
        return USERNAME;
    }

    public static String getPASSWORD() {
        return PASSWORD;
    }

    Lock lock = new ReentrantLock();

    private static FTPUtils INSTANCE;


    private FTPUtils() {


    }

    ;

    public static synchronized FTPUtils getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new FTPUtils();
        }
        return INSTANCE;
    }

    public FTPClient ftpClient = null;

    public void initFtpClient() throws  Exception {
        ftpClient = new FTPClient();
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.enterLocalPassiveMode();
            log.info("connecting...ftp服务器:" + HOSTNAME + ":" + PORT);
            ftpClient.connect(getHOSTNAME(), getPORT()); 			//连接ftp服务器
            ftpClient.login(getUSERNAME(), getPASSWORD()); 			//登录ftp服务器
            int replyCode = ftpClient.getReplyCode(); 				//是否成功登录服务器
            if (!FTPReply.isPositiveCompletion(replyCode)) {
                log.info("connect failed...ftp服务器:  登陆失败" + HOSTNAME + ":" + PORT);
                throw new RuntimeException("登陆失败");
            } else {
                log.info("connect successfu...ftp服务器: 登陆成功" + HOSTNAME + ":" + PORT);

            }

    }


    /**
     * @param pathname    ftp服务保存地址
     * @param fileName    上传到ftp的文件名
     * @param inputStream 输入文件流
     * @return
     */
    public boolean uploadFile(String pathname, String fileName, InputStream inputStream) {
        lock.lock();
        try {
            log.info("开始上传文件");
            initFtpClient();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            CreateDirecroty(pathname);
            ftpClient.makeDirectory(pathname);
            log.info("            ftpClient.makeDirectory(pathname);" + fileName);
            ftpClient.changeWorkingDirectory(pathname);
            log.info("            ftpClient.makeDirectory(pathname);" + fileName);
            ftpClient.setBufferSize(1024*1024);
            BufferedInputStream input = new BufferedInputStream(inputStream);
                ftpClient.storeFile(fileName, input);
                log.info("            ftpClient.makeDirectory(pathname);" + fileName);
            inputStream.close();
            ftpClient.logout();
            log.info("上传文件成功");
        } catch (Exception e) {
            log.info("上传文件失败");
            e.printStackTrace();
            return false;
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream
            ) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            lock.unlock();
        }
        return true;
    }

    //改变目录路径
    public boolean changeWorkingDirectory(String directory) {
        boolean flag = true;
        try {
            flag = ftpClient.changeWorkingDirectory(directory);
            if (flag) {
                log.info("进入文件夹" + directory + " 成功！");
            } else {
                log.info("进入文件夹" + directory + " 失败！开始创建文件夹");
            }
        } catch (Exception ioe) {
            ioe.printStackTrace();
        }
        return flag;
    }

    //创建多层目录文件，如果有ftp服务器已存在该文件，则不创建，如果无，则创建
    public boolean CreateDirecroty(String remote) throws Exception {
        boolean success = true;
        String directory = remote + "/";
        // 如果远程目录不存在，则递归创建远程服务器目录
        if (!"/".equalsIgnoreCase(directory) && !changeWorkingDirectory(new String(directory))) {
            int start = 0;
            int end = 0;
            if (directory.startsWith("/")) {
                start = 1;
            } else {
                start = 0;
            }
            end = directory.indexOf("/", start);
            String path = "";
            String paths = "";
            while (true) {
                String subDirectory = new String(remote.substring(start, end).getBytes("GBK"), "iso-8859-1");
                path = path + "/" + subDirectory;
                if (!existFile(path)) {
                    if (makeDirectory(subDirectory)) {
                        changeWorkingDirectory(subDirectory);
                    } else {
                        log.info("创建目录[" + subDirectory + "]失败");
                        changeWorkingDirectory(subDirectory);
                    }
                } else {
                    changeWorkingDirectory(subDirectory);
                }

                paths = paths + "/" + subDirectory;
                start = end + 1;
                end = directory.indexOf("/", start);
                // 检查所有目录是否创建完毕
                if (end <= start) {
                    break;
                }
            }
        }
        return success;
    }
    public boolean uploadFiles(String pathname) {
        lock.lock();
        try {
            initFtpClient();
            CreateDirecroty(pathname);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }finally {
            lock.unlock();
        }
        return true;
    }
    //判断ftp服务器文件是否存在
    public boolean existFile(String path) throws Exception {
        boolean flag = false;
        FTPFile[] ftpFileArr = ftpClient.listFiles(path);
        if (ftpFileArr.length > 0) {
            flag = true;
        }
        return flag;
    }

    //创建目录
    public boolean makeDirectory(String dir) {

        boolean flag = true;
        try {
        
            flag = ftpClient.makeDirectory(dir);
            if (flag) {
                log.info("创建文件夹" + dir + " 成功！");
            } else {
                log.info("创建文件夹" + dir + " 失败！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    /**
     * 下载文件 *
     *
     * @param pathname  FTP服务器文件目录 *
     * @param filename  文件名称 *
     * @param localpath 下载后的文件路径 *
     * @return
     */
    public boolean downloadFile(String pathname, String filename, String localpath) {
        boolean flag = false;
        OutputStream os = null;
        try {
            log.info("开始下载文件");
            initFtpClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                if (filename.equalsIgnoreCase(file.getName())) {
                    File localFile = new File(localpath + "/" + file.getName());
                    os = new FileOutputStream(localFile);
                    ftpClient.retrieveFile(file.getName(), os);
                    os.close();
                }
            }
            ftpClient.logout();
            flag = true;
            log.info("下载文件成功");
        } catch (Exception e) {
            log.info("下载文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (null != os) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 删除文件 *
     *
     * @param pathname FTP服务器保存目录 *
     * @param filename 要删除的文件名称 *
     * @return
     */
    public boolean deleteFile(String pathname, String filename) {
        boolean flag = false;
        try {
            log.info("开始删除文件");
            initFtpClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            ftpClient.dele(filename);
            ftpClient.logout();
            flag = true;
            log.info("删除文件成功");
        } catch (Exception e) {
            log.info("删除文件失败");
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return flag;
    }

    /**
     * 获取txt文件内容 *
     *
     * @param pathname FTP服务器文件目录 *
     * @param filename 文件名称 *
     * @return 文件内容字符串
     */
    public StringBuilder getTxtData(String pathname, String filename) {
        StringBuilder content = new StringBuilder();
        String str = "";
        OutputStream os = null;
        BufferedReader br = null;
        InputStream is = null;
        try {
            initFtpClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                if (filename.equalsIgnoreCase(file.getName())) {
                    is = ftpClient.retrieveFileStream(file.getName());
                    br = new BufferedReader(new InputStreamReader(is));
                    while ((str = br.readLine()) != null) {
                        content.append(str + "\n");
                    }
                    br.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    /**
     * 获取指定行数的txt文件内容 *
     *
     * @param pathname FTP服务器文件目录 *
     * @param filename 文件名称 *
     * @param rowNum   行数 *
     * @return 文件内容字符串
     */
    public StringBuilder getRowsTxt(String pathname, String filename, Integer rowNum) {
        StringBuilder content = new StringBuilder();
        String str = "";
        BufferedReader br = null;
        InputStream is = null;
        try {
            Integer count = 0;
            initFtpClient();
            //切换FTP目录
            ftpClient.changeWorkingDirectory(pathname);
            FTPFile[] ftpFiles = ftpClient.listFiles();
            for (FTPFile file : ftpFiles) {
                if (filename.equalsIgnoreCase(file.getName())) {
                    is = ftpClient.retrieveFileStream(file.getName());
                    br = new BufferedReader(new InputStreamReader(is));
                    while ((str = br.readLine()) != null) {
                        //每遍历一行，计数+1
                        if (!"".equals(str) && "" != str) {
                            count++;
                        } else {
                            continue;
                        }
                        content.append(str + "\n");
                        if (count.equals(rowNum)) {
                            break;
                        }
                    }
                    br.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return content;
    }

    public void deleteFileFromFtp(String delFileName, String pathname) {
        try {
            initFtpClient();
            ftpClient.changeWorkingDirectory(pathname);
            System.out.println("+++++++++++" + ftpClient.removeDirectory(delFileName));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //删除当前日期8天前的文件夹
    public void deleteDirOrFile(String pathname) {
        try {
            initFtpClient();
            if (pathname == null) {
                return;
            }

            FTPFile[] files = ftpClient.listFiles(pathname);
            for (FTPFile f : files) {
                if (f.isDirectory()) {
                    String dirname = f.getName();
                    //获取内部文件夹名称后格式化处理。判断其时间是否在当前时间的8天前

                    //切换FTP目录，还是当前目录
                    ftpClient.changeWorkingDirectory(pathname);
                    if (dirname == null) {
                        return;
                    }
                    FTPFile[] files2 = ftpClient.listFiles(dirname);
                    for (FTPFile f2 : files2) {
                        if (f2.isFile()) {
                            ftpClient.dele(pathname + "/" + dirname + "/" + f2.getName());
                            System.out.println("删除图片成功");
                        } else if (f2.isDirectory()) {
                            ftpClient.removeDirectory(pathname + "/" + f2);
                            System.out.println("删除子图片文件夹成功");
                        }
                    }
                    ftpClient.removeDirectory(pathname + "/" + f.getName());
                    System.out.println("删除图片文件夹成功");
                }
            }
            return;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}